import styled from '@emotion/styled';
import { Button, Card, Form, Tooltip } from 'antd';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';

import DeleteIcon from '@/assets/icons/delete.svg';
import PlusIcon from '@/assets/icons/plus.svg';
import { Rules } from '@/components/complex/Rules';
import { colors } from '@/config/theme';
import { NODE_TYPE } from '@/constants/config';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';

import { MultipleAssignments } from '../../MultipleAssignments';

const AssignmentItemDiv = styled.div`
  border: 1px solid transparent;

  &:hover {
    border-color: ${colors.gray[300]};
    box-shadow: 0 0 4px ${colors.gray[300]};
  }
`;

export const Assignment = memo(() => {
  const [form] = Form.useForm();
  const { currentAndParentPrivateVariables, currentAndParentPublicVariables, setNodeDataFor, getNodeDataFor } =
    useCurrentNode<NODE_TYPE.RULE>();
  const rightVariables = currentAndParentPrivateVariables.concat(currentAndParentPublicVariables);
  const { systemVars } = useDictStore();
  const variablesWithSystem = systemVars.concat(rightVariables);

  const handleOnDragEnd = (result: any) => {
    if (!result.destination) return;
    const data = getNodeDataFor();

    const items = Array.from(data?.rulesList || []);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setNodeDataFor({ ...data, rulesList: items });
  };

  useEffect(() => {
    const data = getNodeDataFor();
    form.setFieldsValue({ rulesList: data?.rulesList || [] });
  }, [form, getNodeDataFor]);

  return (
    <Card
      size="small"
      title={
        <div>
          条件赋值配置
          <span className="text-12 text-gray-500 ml-4">(相同变量的赋值操作会覆盖之前的赋值, 可拖动调整顺序)</span>
        </div>
      }
      className="assignment mt-12">
      <Form
        onValuesChange={(_, value) => {
          const data = getNodeDataFor();
          setNodeDataFor({ ...data, rulesList: value.rulesList });
        }}
        form={form}>
        <Form.List name="rulesList">
          {(fields, { add, remove }) => (
            <DragDropContext onDragEnd={handleOnDragEnd}>
              <Droppable droppableId="rulesList">
                {(provided) => (
                  <div {...provided.droppableProps} ref={provided.innerRef} className="flex flex-col gap-8">
                    {fields.map(({ key, name, ...restField }, index) => {
                      return (
                        <Draggable draggableId={String(key + name)} key={key} index={index}>
                          {(provided) => (
                            <AssignmentItemDiv
                              ref={provided.innerRef}
                              {...provided.draggableProps}
                              {...provided.dragHandleProps}
                              className="assignment-item">
                              <div className="form-header text-center flex bg-gray-50 py-8 text-14">
                                <div className="text-14 w-[60%] relative">
                                  <span className="assignment-index inline-block w-22 h-22 rounded-[50%] absolute left-12 top-0 bg-primary-400 text-12 text-white">
                                    {index + 1}
                                  </span>
                                  <span className="text-14--bold">条件</span>
                                </div>
                                <div className="text-14--bold w-[40%]">赋值</div>
                                <div className="text-14 w-[40px]">
                                  <Tooltip placement="left" title="删除该行条件赋值">
                                    <div>
                                      <DeleteIcon
                                        fill={colors.red[500]}
                                        className="cursor-pointer"
                                        width={18}
                                        height={18}
                                        onClick={() => remove(name)}
                                      />
                                    </div>
                                  </Tooltip>
                                </div>
                              </div>

                              <div className="flex items-center gap-12 w-full py-8">
                                <Form.Item
                                  className="w-[60%] mb-0 pl-8"
                                  {...restField}
                                  name={[name, 'criteria']}
                                  rules={[{ required: true, message: '请配置规则' }]}>
                                  <Rules leftVariables={variablesWithSystem} rightVariables={rightVariables} fieldSize="small" />
                                </Form.Item>
                                <Form.Item
                                  className="w-[40%] mb-0 pr-8"
                                  {...restField}
                                  name={[name, 'assignments']}
                                  rules={[{ required: true, message: '请选择赋值结构' }]}>
                                  <MultipleAssignments
                                    leftVariables={variablesWithSystem}
                                    rightVariables={variablesWithSystem}
                                    fieldSize="small"
                                    fieldMode="assignment"
                                  />
                                </Form.Item>
                              </div>
                            </AssignmentItemDiv>
                          )}
                        </Draggable>
                      );
                    })}
                    {provided.placeholder}
                    <Form.Item className="mt-12">
                      <Button type="dashed" onClick={() => add()} block>
                        <PlusIcon width={12} height={12} />
                        新增条件赋值
                      </Button>
                    </Form.Item>
                  </div>
                )}
              </Droppable>
            </DragDropContext>
          )}
        </Form.List>
      </Form>
    </Card>
  );
});
